﻿using PwjCy.Lite.Common;
using PwjCy.Lite.Core.Imp;
using PwjCy.Log;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace PwjCy.Lite.Core
{
    /// <summary>
    /// 服务端口
    /// </summary>
    public sealed class ServiceHub : ServiceContainer, IServiceHub, IServiceContainer, IServiceProvider
    {
        private static readonly Lazy<ServiceHub> lazy = new Lazy<ServiceHub>(() => new ServiceHub());
        private ServiceHub() { }
        /// <summary>
        /// 服务端口实例
        /// </summary>
        public static ServiceHub Instance { get { return lazy.Value; } }
        /// <summary>
        /// 日志服务
        /// </summary>
        public static ILogger LoggerService
        {
            get { return LogHelper.GetLogger("WolfLite"); }
        }
        public void Load()
        {
            throw new NotImplementedException();
        }

        public void UnLoad()
        {
            throw new NotImplementedException();
        }

        public void Init(bool refresh)
        {
            Init(refresh, false);
        }
        /// <summary>
        /// 初始化服务
        /// </summary>
        /// <param name="refresh">恢复</param>
        /// <param name="sync">同步</param>
        public void Init(bool refresh, bool sync)
        {
            try
            {
                BootServices services = LiteCoreHelper.GetObjectSetting<BootServices>(LiteCoreHelper.BootConfigPath);
                foreach (BootConfig bc in services.service)
                {
                    try
                    {
                        string[] types = bc.type.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        string[] drivers = bc.driver.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        HashCacheHelper.Instance.AddCache<object>(Assembly.Load(drivers[1]).CreateInstance(drivers[0]), types[0]);
                        ServiceHub.LoggerService.Info(string.Format("Service Load {0},{1}", drivers[0], drivers[1]));
                    }
                    catch (Exception innerEx)
                    {
                        ServiceHub.LoggerService.Error("初始化服务时异常", innerEx);
                    }
                }
            }
            catch (Exception ex)
            {
                ServiceHub.LoggerService.Error("初始化服务时异常", ex);
            }

        }
    }
}
